package com.kuang.controller;

import com.kuang.common.exception.ValidationException;
import com.kuang.entity.User;
import com.kuang.service.user.UserService;
import com.kuang.utils.MD5Util;
import com.kuang.utils.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class LoginController {


    @Autowired
    private UserService userService;


    @PostMapping("/session/login")
    public String sessionlogin(String username, String password, HttpSession session){
        //1 : 校验username和password是否为空

        //2： 根据用户查询用户是否存在
        User user = userService.getByUserName(username);
        if(user == null){
            throw  new ValidationException(403,"用户名或密码有误!!!");
        }

        //3：对密码进行加密加盐进行处理
        password = MD5Util.md5slat(password);

        //如果用户输入的密码和数据库查询到密码不一致
        if(!password.equalsIgnoreCase(user.getPassword())){
            throw  new ValidationException(403,"用户名或密码有误!!!");
        }

        // 4: 如果登录成功就写入session会话中
        // 用户信息写入到服务端用session的方法来存储的 cookie
        session.setAttribute("session_user",user);

        return "success";
    }


}
